
# Create your views here.
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from student.models import Student
# 导入序列化器
# from rest_framework.serializers import Serializer

#  我们这里直接导入serializers  下面我们写字段的时候 需要用到
from rest_framework import serializers
from score.models import Score
from course.models import Course
from teacher.models import Teacher
from teacher_course_class.models import TeacherCourseClass

# 成绩序列化器
class GradeSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    course = serializers.CharField(source='course.name', read_only=True)
    value = serializers.FloatField(read_only=True)
    teacher = serializers.SerializerMethodField()
    
    def get_teacher(self, obj):
        """获取该学生该课程的授课教师"""
        try:
            # 通过学生所在班级和课程查找授课教师
            student = obj.student
            course = obj.course
            
            # 如果学生有班级，则通过班级查找
            if student.clazz:
                teacher_course_class = TeacherCourseClass.objects.filter(
                    course=course,
                    clazz=student.clazz
                ).first()
                
                if teacher_course_class:
                    return teacher_course_class.teacher.name
            
            # 如果没有找到，返回空字符串
            return ""
        except Exception:
            return ""

#  使用ModelSerializer的简化版本
class StudentModelSerializer(serializers.ModelSerializer):
    # 添加可读字段
    clazz_name = serializers.CharField(source='clazz.name', read_only=True)
    department_name = serializers.CharField(source='department.name', read_only=True)
    sex_display = serializers.SerializerMethodField()
    grades = serializers.SerializerMethodField()
    
    class Meta:
        model = Student
        fields = ['id', 'student_num', 'name', 'sex', 'sex_display', 'age', 'clazz', 'clazz_name', 
                 'department', 'department_name', 'description', 'created_at', 'grades']
        # 设置字段为可选，避免因为必填字段缺失导致的验证错误
        extra_kwargs = {
            'description': {'required': False},
            'student_num': {'required': False}  # 学号可选，兼容已存在数据
        }
    
    def get_sex_display(self, obj):
        return '男' if obj.sex else '女'
    
    def get_grades(self, obj):
        """获取学生的所有成绩"""
        scores = Score.objects.filter(student=obj)
        serializer = GradeSerializer(scores, many=True)
        return serializer.data




class StudentViewSet(ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer
    # 临时移除认证要求，方便测试
    # permission_classes = [IsAuthenticated]
    # get 列表
    # 重写响应格式
    def list(self, request, *args, **kwargs):
        response = super().list(request, *args, **kwargs)
        res = {
            'status': 200,
            'data': {
                'info': response.data,
                'message': '查找成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)
    #
    def retrieve(self, request, *args, **kwargs):
        # 使用默认的retrieve逻辑获取学生实例
        instance = self.get_object()
        
        # 序列化学生信息（包含成绩信息）
        serializer = self.get_serializer(instance)
        
        res = {
            'status': 200,
            'data': {
                'info': serializer.data,
                'message': '查找成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)

    # post 添加
    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        res = {
            'status': 200,
            'data': {
                'info': response.data,
                'message': '添加成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)
    # put 修改单个
    def update(self, request, *args, **kwargs):
        response = super().update(request, *args, **kwargs)
        res = {
            'status': 200,
            'data': {
                'info': response.data,
                'message': '更新成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)
    # delete 删除单个
    def destroy(self, request, *args, **kwargs):
        try:
            response = super().destroy(request, *args, **kwargs)
            res = {
                'status': 200,
                'data': {
                    'info': {},
                    'message': '删除成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 404,
                'data': {
                    'info': {},
                    'message': '学生未找到'
                }
            }
            return Response(res, status=status.HTTP_404_NOT_FOUND)
    
    # 自定义action：按班级筛选学生
    @action(detail=False, methods=['get'])
    def by_class(self, request):
        """根据班级ID获取学生列表"""
        class_id = request.query_params.get('class_id')
        if class_id:
            students = self.queryset.filter(clazz_id=class_id)
        else:
            students = self.queryset
        
        serializer = self.get_serializer(students, many=True)
        res = {
            'status': 200,
            'data': {
                'info': serializer.data,
                'message': '查找成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)
    
    # 自定义action：获取学生统计信息
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取学生统计信息"""
        total_count = self.queryset.count()
        male_count = self.queryset.filter(sex=1).count()
        female_count = self.queryset.filter(sex=0).count()
        
        res = {
            'status': 200,
            'data': {
                'info': {
                    'total_count': total_count,
                    'male_count': male_count,
                    'female_count': female_count
                },
                'message': '统计信息获取成功'
            }
        }
        return Response(res, status=status.HTTP_200_OK)

# ... existing code ...
